// pages/search/search.js
import { REQUEST_SEARCH_DEFAULT, REQUEST_SEARCH_HOT_DETAIL, REQUEST_SEARCH } from '../../api/index.js'
import { setStorageSync, getStorageSync, removeStorageSync, showModal, isEmptyObject} from '../../utils/util.js'
let isSend = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent: '',
    hotList: [],
    searchContent: '',
    searchList: [],
    historyList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getInitData();
    const localHistory = getStorageSync('searchHistory');
    this.setData({
      historyList: isEmptyObject(localHistory) ? [] : localHistory
    });
  },
  async getInitData() {
    const { data: { showKeyWord } } = await REQUEST_SEARCH_DEFAULT();
    const { data } = await  REQUEST_SEARCH_HOT_DETAIL();
    this.setData({ placeholderContent: showKeyWord, hotList: data });
  },
  handleInputChange(evt) {
    const { historyList } = this.data;
    const searchContent = evt.detail.value.trim();
    isSend && clearTimeout(isSend);
    if (!searchContent) return this.setData({ searchContent: '', searchList: [] });
    isSend = setTimeout(async () => {
      const { result } = await REQUEST_SEARCH({ keywords: searchContent, limit: 10 });
      const index = historyList.indexOf(searchContent);
      if (index !== -1) {
        historyList.splice(index, 1);
      }
      historyList.unshift(searchContent);
      setStorageSync('searchHistory', historyList);
      this.setData({ searchContent, historyList, searchList: result.songs });
    }, 300);
  },
  clearSearchContent() {
    this.setData({ searchContent: '', searchList: [] });
  },
  async bindDelSearchHistory() {
    const confirm = await showModal({content: "确认删除吗？"});
    this.setData({ historyList: [] });
    confirm && removeStorageSync('searchHistory');
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})